package com.pactera.asmp.server.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

/**
 *  Base64工具类
 */
public class Base64Util {
    private static final Logger logger = LoggerFactory.getLogger(Base64Util.class);

    private static final String CHARSET = "utf-8";

    private Base64Util(){}
    /**
     * 解密
     *
     * @param data
     * @return
     */
    public static String decode(String data) {
        try {
            if (null == data) {
                return null;
            }

            return new String(Base64.decodeBase64(data.getBytes(CHARSET)), CHARSET);
        } catch (UnsupportedEncodingException e) {
            logger.error(String.format("字符串：%s，解密异常", data), e);
        }

        return null;
    }

    /**
     * 加密
     *
     * @param data
     * @return
     */
    public static String encode(String data) {
        try {
            if (null == data) {
                return null;
            }
            return new String(Base64.encodeBase64(data.getBytes(CHARSET)), CHARSET);
        } catch (UnsupportedEncodingException e) {
            logger.error(String.format("字符串：%s，加密异常", data), e);
        }

        return null;
    }

    /**
     * 加密pwd
     * @param pwd
     * @param userName
     * @return
     */
    public static String encodePwd(String pwd, String userName) {
        if(StringUtils.isEmpty(userName)|| StringUtils.isEmpty(pwd)) {
            return null;
        }
        try {
            String process1 = new String(Base64.encodeBase64(pwd.getBytes(CHARSET)));
            return new String(Base64.encodeBase64(process1.concat(userName.substring(0, 1)).getBytes(CHARSET)));
        } catch (UnsupportedEncodingException e) {
            logger.error(String.format("pwd：%s,userName：%s,加密异常", pwd, userName), e);
        }

        return null;
    }

    /**
     * 解密
     * @param pwd
     * @return
     */
    public static String decodePwd(String pwd) {
        try {
            if(StringUtils.isEmpty(pwd)) {
                return null;
            }
            String process1 = decode(pwd);
            if(StringUtils.isEmpty(process1)) {
                logger.error(String.format("pwd：%s：%s.解密失败", pwd));
                return null;
            }
            return decode(process1.substring(0, process1.length() - 1));
        }catch (Exception e) {
            logger.error(String.format("pwd：%s：%s,解密异常", pwd), e);
        }
        return null;
    }
}
